package com.smsc.headend.task.engine.handler.impl.deviceconfig;

import com.smsc.headend.module.data.enums.OperationGroup;
import com.smsc.headend.module.data.enums.OperationName;
import com.smsc.headend.module.protocol.DeviceData;
import com.smsc.headend.module.task.dto.AtomicTask;
import com.smsc.headend.module.task.dto.Task;
import com.smsc.headend.module.template.alarmfilter.entity.enums.AlarmFilterEnum;
import com.smsc.headend.task.engine.dao.TaskDAO;
import com.smsc.headend.task.engine.exception.UDISTaskHandlerException;
import com.smsc.headend.task.engine.handler.TaskHandler;
import com.smsc.headend.task.engine.service.CosemXmlService;
import com.smsc.headend.task.engine.service.FeignAssetManagementService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * @author wxh
 * @date 2021/1/25
 */
@Slf4j
public class SetAlarmHandler implements TaskHandler {
    @Autowired
    CosemXmlService cosemXmlService;
    @Autowired
    FeignAssetManagementService assetManagementService;
    @Autowired
    TaskDAO taskDAO;

    @Override
    public int handle(Task task, AtomicTask atomicTask, DeviceData deviceData, String actionResult) throws UDISTaskHandlerException {
        log.info("{} action result {}", atomicTask.getAtomicTaskNo(), actionResult);

        OperationName operationName = OperationName.forId(atomicTask.getOperationId());
        switch (operationName) {
            case SetData:
                AlarmFilterEnum alarmFilterEnum = AlarmFilterEnum.forId(atomicTask.getSeq() + 1);
                String key = "";
                if (alarmFilterEnum == null) {
                    log.info("AlarmFilterEnum not found {}", atomicTask.getSeq());
                } else {
                    key = alarmFilterEnum.getName();
                }
                taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), key, "Success", 600l, Boolean.TRUE);
                if (isSubTaskGroupLastAtomicTask(task, atomicTask)){
                    taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), "subTaskCompleted", true,600L, true);
                }
                break;
        }
        return 1;
    }

    @Override
    public int handleFailure(Task task, AtomicTask atomicTask, String message) {
        log.info("error {}, ", message);
        if (atomicTask.getGroupId() == OperationGroup.AlarmFilterSet.getId().intValue()) {
            AlarmFilterEnum alarmFilterEnum = AlarmFilterEnum.forId(atomicTask.getSeq() + 1);
            String stepOperationName = (alarmFilterEnum == null) ? "message" : alarmFilterEnum.getName();
            taskDAO.addTaskData(task.getTaskNo(), atomicTask.getAtomicTaskNo(), stepOperationName, String.format("[%s]", message), 3600l, false);
        }
        return -1;
    }
}
